package com.cola.custSpeechTranscription.api;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @BelongsProject: custSpeechTranscription
 * @BelongsPackage: com.cola.custSpeechTranscription.api
 * @Author: jiangkang
 * @CreateTime: 2025-10-30  15:35
 * @Description: TODO
 * @Version: 1.0
 */
@Component
public class CustShareWebSocketHandler extends TextWebSocketHandler {

    private static final Logger log = LoggerFactory.getLogger("LCAP_EXTENSION_LOGGER");

    @Autowired
    private CustShareSessionManager shareSessionManager;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 从URL参数中获取shareId
        String shareId = getShareIdFromRequest(session);
        log.info("[分享观看连接] 建立连接 sessionId={}, shareId={}", session.getId(), shareId);

        if (shareId == null || shareId.trim().isEmpty()) {
            sendErrorMessage(session, "缺少分享ID参数");
            session.close(CloseStatus.NOT_ACCEPTABLE);
            return;
        }

        session.getAttributes().put("shareId", shareId);

        // 自动处理观看者加入
        boolean success = shareSessionManager.handleViewerConnection(shareId, session);

        if (!success) {
            // 如果自动加入失败，发送错误消息并关闭连接
            sendErrorMessage(session, "分享会话不存在或已结束");
            session.close(CloseStatus.NOT_ACCEPTABLE);
            return;
        }
    }

    /**
     * 从请求URL中获取shareId参数
     */
    private String getShareIdFromRequest(WebSocketSession session) {
        try {
            // 首先尝试从查询参数获取
            String query = session.getUri().getQuery();
            if (query != null) {
                String[] params = query.split("&");
                for (String param : params) {
                    if (param.startsWith("shareId=")) {
                        return param.substring(8); // "shareId=".length
                    }
                }
            }

            // 如果URL参数中没有，尝试从路径中提取
            String path = session.getUri().getPath();
            if (path != null) {
                String[] pathSegments = path.split("/");
                for (int i = 0; i < pathSegments.length - 1; i++) {
                    if ("custShare".equals(pathSegments[i]) && i + 1 < pathSegments.length) {
                        String potentialShareId = pathSegments[i + 1];
                        // 简单的验证，确保不是空字符串
                        if (potentialShareId != null && !potentialShareId.trim().isEmpty()) {
                            return potentialShareId;
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("[获取shareId] 从请求中解析shareId失败", e);
        }
        return null;
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        log.info("[分享观看消息] sessionId={}，收到消息：{}", session.getId(), payload);

        try {
            JSONObject jsonMessage = new JSONObject(payload);
            String type = jsonMessage.optString("type");

            if ("ping".equals(type)) {
                handlePing(session);
            } else if ("get_session_info".equals(type)) {
                handleGetSessionInfo(session);
            } else {
                log.info("[分享观看消息] 未知消息类型: {}", type);
                sendErrorMessage(session, "不支持的消息类型: " + type);
            }
        } catch (Exception e) {
            log.error("[分享观看消息] 解析消息异常", e);
            sendErrorMessage(session, "消息格式错误");
        }
    }

    private void handlePing(WebSocketSession session) {
//        JSONObject response = new JSONObject();
//        response.put("type", "pong");
//        response.put("timestamp", System.currentTimeMillis());
//        sendMessage(session, response.toString());
    }

    private void handleGetSessionInfo(WebSocketSession session) {
        // 可以在这里返回会话的详细信息
        JSONObject response = new JSONObject();
        response.put("type", "session_info_response");
        response.put("sessionId", session.getId());
        response.put("timestamp", System.currentTimeMillis());
        sendMessage(session, response.toString());
    }

    private void sendErrorMessage(WebSocketSession session, String error) {
        JSONObject response = new JSONObject();
        response.put("type", "error");
        response.put("message", error);
        sendMessage(session, response.toString());
    }

    private void sendMessage(WebSocketSession session, String message) {
        if (session.isOpen()) {
            try {
                session.sendMessage(new TextMessage(message));
            } catch (IOException e) {
                log.error("[发送消息] 失败 sessionId={}", session.getId(), e);
            }
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("[分享观看断开] sessionId={}，状态={}，开始清理", session.getId(), status);

        String shareId = (String) session.getAttributes().get("shareId");
        shareSessionManager.updateShareStatus("0",null,shareId);

        // 立即清理观看会话相关资源
        shareSessionManager.cleanupOnViewSessionClosed(session);

        log.info("[分享观看断开清理完成] sessionId={}", session.getId());

    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.error("[分享观看传输错误] sessionId={}", session.getId(), exception);
    }

}